import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import SmartDetentionSystem from '@/views/SmartDetentionSystem.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      requiresAuth: true
    }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/views/About.vue'),
    meta: {
      title: '关于我们',
      requiresAuth: true
    }
  },
  {
    path: '/smart-detention',
    name: 'SmartDetentionSystem',
    component: SmartDetentionSystem,
    meta: {
      title: '智能收押分流系统',
      requiresAuth: true
    }
  }
]

const router = new VueRouter({
  mode: 'history', // 使用 history 模式，去掉 URL 中的 #
  base: process.env.BASE_URL,
  routes,
  // 滚动行为
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 可视化数据大屏`
  }

  // 认证检查逻辑
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查用户是否已登录
    let isAuthenticated = store.getters['user/isAuthenticated']

    // 如果store中没有认证状态，尝试从本地存储恢复
    if (!isAuthenticated) {
      await store.dispatch('user/checkAuth')
      isAuthenticated = store.getters['user/isAuthenticated']
    }

    if (!isAuthenticated) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原始路径，登录后跳转回来
      })
      return
    }
  }

  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && store.getters['user/isAuthenticated']) {
    next('/')
    return
  }

  next()
})

// 全局后置守卫
router.afterEach((to, from) => {
  // 可以在这里添加页面访问统计等逻辑
  console.log(`导航到: ${to.name}`)
})

export default router

